package com.hzit.loan.manager.aspect;

import com.hzit.loan.manager.annon.TargetDataSource;
import com.hzit.loan.manager.config.DynamicDataSourceContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/***
 * 切面类
 */
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {


    /**
     *
     * @param point
     * @param ds
     * @throws Throwable
     */
    @Before("@annotation(ds)")
    public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
        String name = ds.name();
        System.out.println("-------------数据源名字：" + name);

        if (!DynamicDataSourceContextHolder.containsDataSource(name)){
            System.out.println("数据源已经存在");
        }else{
            DynamicDataSourceContextHolder.setDataSourceType(name);
        }
    }

    @After("@annotation(ds)")
    public void clearDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
        System.out.println("------------清除数据源----");
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}
